<template>
  <el-dialog :title="title" :visible="showDialog" @update:visible="$emit('update:show-dialog')">
    <el-form ref="formData" :model="formData" :rules="formRules" :label-width="formLabelWidth">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="formData.name" placeholder="1-30个字符" style="width: 80%" autocomplete="off" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="formData.code" style="width: 80%" autocomplete="off" placeholder="1-30个字符" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select v-model="formData.manager" style="width: 80%" placeholder="请选择部门负责人" @focus="getSimplePeople">
          <el-option v-for="({username, id}) in people" :key="id" :label="username" :value="username" />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input
          v-model="formData.introduce"
          placeholder="1-50个字符"
          type="textarea"
          style="width: 80%"
          autocomplete="off"
        />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="oncancel">取 消</el-button>
      <el-button type="primary" @click="submit">确 定</el-button>
    </div>
  </el-dialog>
</template>
<script>
import {
  addDepartments,
  getDepartDetail,
  getDepartments,
  getEmployeeSimple,
  updateDepartments
} from '@/api/departments'

export default {
  props: {
    treeNode: {
      type: Object,
      required: true
    },
    showDialog: {
      type: Boolean,
      defaultValue: false
    }
  },
  data() {
    const checkNameRepeat = async(rule, value, callback) => {
      const { depts } = await getDepartments()
      const { id } = this.formData
      let isRepeat = false
      // 编辑的判断逻辑
      if (id) {
        // 需要把自己过滤掉再去做判断
        // 除了我以外，同一级部门不能再能有叫张三的人
        isRepeat = depts.filter(item => item.pid === this.treeNode.pid && item.id !== id).some(item => item.name === value)
      } else {
        // 新增的判断逻辑
        isRepeat = depts.filter(item => item.pid === this.treeNode.id).some(item => item.name === value)
      }

      return isRepeat ? callback(new Error(`同级已经有了${this.formData.name}`)) : callback()
    }

    const checkCodeRepeat = async(rule, value, callback) => {
      const { depts } = await getDepartments()
      const { id } = this.formData
      // 只有value存在并且value等于其他部门的code的时候才说明重复
      // 如果value不存在的情况下，永远不重复

      let isRepeat = false
      if (id) {
        // 编辑模式下面 如果code重复了 ，还要判断这条数据是不是自身，如果是自身还是忽略
        isRepeat = depts.some(item => item.id !== id && item.code === value && value)
      } else {
        isRepeat = depts.some(item => item.code === value && value)
      }
      return isRepeat ? callback(new Error(`同级已经有了编码${value}`)) : callback()
    }
    return {
      people: [], // 部门负责人下拉款数据
      formRules: {
        name: [
          { required: true, message: '请输入部门名称', trigger: 'blur' },
          { min: 1, max: 30, message: '字符长度不符合规则', trigger: 'blur' },
          {
            validator: checkNameRepeat,
            trigger: 'blur'
          }
        ],
        code: [
          { required: true, message: '请输入部门编码', trigger: 'blur' },
          { min: 1, max: 30, message: '字符长度不符合规则', trigger: 'blur' },
          {
            validator: checkCodeRepeat,
            trigger: 'blur'
          }
        ],
        manager: [
          { required: true, message: '请选择部门负责人', trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '请输入部门介绍', trigger: 'blur' },
          { min: 1, max: 50, message: '字符长度不符合规则', trigger: 'blur' }
        ]
      },
      dialogFormVisible: true,
      formData: {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      },
      formLabelWidth: '120px'
    }
  },
  computed: {
    title() {
      const { id } = this.formData
      return id ? '编辑部门' : '新增部门'
    }
  },
  methods: {
    async getDetailById(id) {
      this.formData = await getDepartDetail(id)
    },
    oncancel() {
      this.$emit('update:show-dialog', false)
      this.$refs.formData.resetFields()

      //  取消的时候还需要重置数据
      this.formData = {
        name: '',
        manager: '',
        code: '',
        introduce: ''
      }
    },
    async getSimplePeople() {
      const res = await getEmployeeSimple()
      console.log(res)
      this.people = res
    },
    async submit() {
      // 判断是否为登录
      const isAdd = !this.formData.id
      await this.$refs.formData.validate()

      if (isAdd) {
        await addDepartments({
          ...this.formData,
          pid: this.treeNode.id
        })
      } else {
        console.log('开始编辑')
        await updateDepartments(this.formData)
      }

      // 重新获取数据
      this.$emit('getDep')

      // 关闭弹框
      this.$emit('update:show-dialog', false)
    }
  }
}
</script>
